<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label-width="100" label="所属活动组" prop="activityName">
        <el-input v-model="queryParams.activityGroupName" placeholder="请输入活动组名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>

      <el-form-item label="活动名称" prop="activityName">
        <el-input v-model="queryParams.activityName" placeholder="请输入活动名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="活动类型" prop="activityType">
        <el-select v-model="queryParams.activityType" placeholder="活动类型" clearable>
          <el-option label="满减活动" value="2" />
          <el-option label="折扣活动" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="活动状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="活动状态" clearable>
          <el-option label="进行中" value="1" />
          <el-option label="未开始" value="0" />
          <el-option label="已结束" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['market:activity:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['market:activity:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['market:activity:remove']">删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="activityList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="所属活动组" align="center" prop="activityGroupName" />
      <el-table-column label="活动名称" align="center" prop="activityName" />
      <el-table-column label="活动类型" align="center" prop="activityType">
        <template #default="scope">
          <dict-tag :options="activity_type" :value="scope.row.activityType" />
        </template>
      </el-table-column>

      <el-table-column label="优惠值" align="center" prop="value" />

      <el-table-column label="活动海报" align="center" prop="posterUrl" width="120">
        <template #default="scope">
          <el-image v-if="scope.row.posterUrl" :src="scope.row.posterUrl" :preview-src-list="[scope.row.posterUrl]"
            preview-teleported fit="cover" style="width: 80px; height: 80px; border-radius: 5px;" hide-on-click-modal />
          <span v-else>暂无海报</span>
        </template>
      </el-table-column>

      <el-table-column label="开始时间" align="center" prop="startTime" width="180" />
      <el-table-column label="结束时间" align="center" prop="endTime" width="180" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="activity_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="200">
        <template #default="scope">
          <el-tooltip content="详情" placement="top">
            <el-button link type="primary" icon="View" @click="handleView(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip content="修改" placement="top">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['market:activity:edit']"></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
              v-hasPermi="['market:activity:remove']"></el-button>
          </el-tooltip>
          <el-tooltip content="上传海报" placement="top">
            <el-button link type="primary" icon="Upload" @click="handleUploadPoster(scope.row)"
              v-hasPermi="['market:activity:edit']"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加/编辑活动对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="addFormRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="活动ID" prop="activityId" v-if="isEdit">
              <el-input v-model="form.activityId" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属活动组" prop="activityGroupId">
              <el-select v-model="form.activityGroupId" placeholder="请选择活动组">
                <el-option v-for="item in activityGroupOptions" :key="item.value" :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="活动名称" prop="activityName">
              <el-input v-model="form.activityName" placeholder="请输入活动名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="活动类型" prop="activityType">
              <el-select v-model="form.activityType" placeholder="请选择活动类型">
                <el-option v-for="item in activityTypeOptions" :key="item.value" :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="优惠值" prop="value">
              <el-input v-model="form.value" placeholder="请输入优惠值" />
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker v-model="form.startTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择开始时间"
                style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker v-model="form.endTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择结束时间"
                style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="海报图片" prop="posterUrl">
              <image-upload v-model="form.posterUrl" :limit="1" @uploaded="handlePosterUploaded" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="活动描述" prop="activityDesc">
              <el-input v-model="form.activityDesc" type="textarea" placeholder="请输入活动描述" :rows="4" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 海报上传对话框 -->
    <el-dialog :title="'上传海报【' + posterUpload.activityName + '】'" v-model="posterUpload.open" width="500px"
      append-to-body>
      <el-form ref="posterFormRef">
        <el-form-item label="活动海报" prop="posterFile">
          <image-upload v-model="posterUpload.posterFile" :limit="1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitPosterForm">确 定</el-button>
          <el-button @click="cancelPoster">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Activity">
import { listProductActivity, delProductActivity, addProductActivity, updateProductActivity, getProductActivity, uploadActivityPoster } from "@/api/market/activity";
import { listGroup } from "@/api/market/activityGroup";
import { useRouter } from 'vue-router';
const router = useRouter();

const { proxy } = getCurrentInstance();

const activityList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const addFormRef = ref();
const isEdit = ref(false); // 是否为编辑状态

// 活动类型字典
const activity_type = ref([
  { label: "折扣活动", value: "1", elTagType: "primary" },
  { label: "满减活动", value: "2", elTagType: "success" }
]);

// 活动状态字典
const activity_status = ref([
  { label: "未开始", value: "0", elTagType: "warning" },
  { label: "进行中", value: "1", elTagType: "success" },
  { label: "已结束", value: "2", elTagType: "info" }
]);

// 活动类型选项
const activityTypeOptions = ref([
  { label: "折扣活动", value: "1" },
  { label: "满减活动", value: "2" }
]);

// 状态选项
// const statusOptions = ref([
//   { label: "未开始", value: "0" },
//   { label: "进行中", value: "1" },
//   { label: "已结束", value: "2" }
// ]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    activityName: null,
    activityGroupName: null,
    activityType: null,
    status: undefined
  },
  rules: {
    activityName: [
      { required: true, message: "活动名称不能为空", trigger: "blur" }
    ],
    activityType: [
      { required: true, message: "活动类型不能为空", trigger: "change" }
    ],
    value: [
      { required: true, message: "优惠值不能为空", trigger: "blur" }
    ],
    startTime: [
      { required: true, message: "开始时间不能为空", trigger: "change" }
    ],
    endTime: [
      { required: true, message: "结束时间不能为空", trigger: "change" }
    ],
    // 状态字段为字符串类型："0"未开始，"1"进行中，"2"已结束
    status: [
      { required: true, message: "活动状态不能为空", trigger: "change" }
    ]
  }
});

// 海报上传相关状态
const posterUpload = reactive({
  open: false,
  activityId: undefined,
  activityName: undefined,
  url: undefined
});

const { queryParams, form, rules } = toRefs(data);

/** 查询活动列表 */
function getList() {
  loading.value = true;
  listProductActivity(queryParams.value).then(response => {
    activityList.value = response.rows || response.data;
    total.value = response.total;
    loading.value = false;
  }).catch(error => {
    console.error('获取活动列表失败:', error);
    proxy.$modal.msgError("获取活动列表失败，请联系管理员");
    loading.value = false;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.activityId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  isEdit.value = false;
  open.value = true;
  title.value = "添加活动";
  reset();
}

/** 修改按钮操作 */
function handleUpdate(row) {
  const activityId = row.activityId || ids.value[0];
  if (!activityId) {
    proxy.$modal.msgWarning("请选择要修改的数据");
    return;
  }

  isEdit.value = true;
  open.value = true;
  title.value = "修改活动";
  reset();

  // 获取活动详细信息
  getProductActivity(activityId).then(response => {
    form.value = response.data;
    // 处理海报URL，确保它是一个字符串而不是对象数组
    if (form.value.posterUrl && Array.isArray(form.value.posterUrl) && form.value.posterUrl.length > 0) {
      form.value.posterUrl = form.value.posterUrl[0].url;
    } else if (form.value.posterUrl && typeof form.value.posterUrl === 'object' && form.value.posterUrl.url) {
      form.value.posterUrl = form.value.posterUrl.url;
    }

    // 确保活动类型和状态是字符串类型，以便下拉框能正确显示
    if (form.value.activityType !== undefined && form.value.activityType !== null) {
      form.value.activityType = form.value.activityType.toString();
    }
    if (form.value.status !== undefined && form.value.status !== null) {
      form.value.status = form.value.status.toString();
    }
  }).catch(error => {
    console.error("获取活动详情失败:", error);
    proxy.$modal.msgError("获取活动详情失败");
  });
}

/** 打开海报上传对话框 */
function openPosterUpload(row) {
  posterUpload.activityId = row.activityId;
  posterUpload.activityName = row.activityName;
  posterUpload.url = row.posterUrl;
  posterUpload.open = true;
}

/** 提交海报上传 */
function submitPoster() {
  const formData = {
    activityId: posterUpload.activityId,
    posterUrl: posterUpload.url
  };

  uploadActivityPoster(formData).then(response => {
    proxy.$modal.msgSuccess("海报上传成功");
    posterUpload.open = false;
    getList();
  }).catch(error => {
    console.error("海报上传失败:", error);
    proxy.$modal.msgError("海报上传失败");
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const activityIds = row.activityId || ids.value;
  proxy.$modal.confirm('是否确认删除活动编号为"' + activityIds + '"的数据项？').then(function () {
    return delProductActivity(activityIds);
  }).then(response => {
    if (response.code === 200) {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    } else {
      proxy.$modal.msgError("删除失败: " + response.msg);
    }
  }).catch(error => {
    console.error("删除活动失败:", error);
    proxy.$modal.msgError("删除失败: " + (error.message || "未知错误"));
  });
}

// 表单重置
function reset() {
  form.value = {
    activityId: undefined,
    activityName: undefined,
    activityType: undefined,
    startTime: undefined,
    endTime: undefined,
    activityDesc: undefined,
    posterUrl: undefined,
    status: "0"
  };
  proxy.resetForm("addFormRef");
}

// 处理海报上传后的URL
function handlePosterUploaded(url) {
  form.value.posterUrl = url;
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 海报上传按钮操作
function handleUploadPoster(row) {
  posterUpload.activityId = row.activityId;
  posterUpload.activityName = row.activityName;
  posterUpload.posterFile = row.posterUrl;
  posterUpload.open = true;
}

// 取消海报上传
function cancelPoster() {
  posterUpload.open = false;
  resetPoster();
}

// 重置海报上传表单
function resetPoster() {
  posterUpload.activityId = undefined;
  posterUpload.activityName = undefined;
  posterUpload.posterFile = undefined;
}

// 提交海报上传表单
function submitPosterForm() {
  // 从ImageUpload组件获取文件URL
  if (!posterUpload.posterFile) {
    proxy.$modal.msgError("请上传活动海报");
    return;
  }

  // ImageUpload组件返回的是图片URL数组或字符串
  // 我们需要获取实际的文件对象
  let file = null;
  if (Array.isArray(posterUpload.posterFile)) {
    if (posterUpload.posterFile.length > 0) {
      // 如果是文件对象数组
      file = posterUpload.posterFile[0].raw || null;
    }
  } else if (posterUpload.posterFile.raw) {
    // 如果是文件对象
    file = posterUpload.posterFile.raw;
  }

  if (!file) {
    proxy.$modal.msgError("请重新选择要上传的海报图片");
    return;
  }

  uploadActivityPoster(posterUpload.activityId, file).then(response => {
    proxy.$modal.msgSuccess("海报上传成功");
    cancelPoster();
    getList();
  }).catch(error => {
    console.error("海报上传失败:", error);
    proxy.$modal.msgError("海报上传失败");
  });
}

/** 查看详情按钮操作 */
function handleView(row) {
  router.push(`/market/activity/detail/${row.activityId}`);
}

// 提交表单
function submitForm() {
  proxy.$refs.addFormRef.validate(valid => {
    if (valid) {
      // 处理表单数据，确保posterUrl是字符串
      const submitData = { ...form.value };

      // 处理海报URL - 如果是图片上传组件返回的数组，则提取URL
      if (submitData.posterUrl && Array.isArray(submitData.posterUrl)) {
        if (submitData.posterUrl.length > 0) {
          submitData.posterUrl = submitData.posterUrl[0].url || submitData.posterUrl[0];
        } else {
          submitData.posterUrl = null;
        }
      } else if (submitData.posterUrl && typeof submitData.posterUrl === 'object' && submitData.posterUrl.url) {
        submitData.posterUrl = submitData.posterUrl.url;
      }

      if (isEdit.value) {
        // 编辑活动 - 使用JSON格式
        updateProductActivity(submitData).then(response => {
          proxy.$modal.msgSuccess("修改活动成功");
          open.value = false;
          getList();
        }).catch(error => {
          console.error("修改活动失败:", error);
          proxy.$modal.msgError("修改活动失败");
        });
      } else {
        // 新增活动 - 使用multipart/form-data格式
        const formData = new FormData();

        // 将活动数据转换为JSON字符串并添加到'activity'字段
        const activityData = { ...submitData };

        formData.append('activity', new Blob([JSON.stringify(activityData)], {
          type: 'application/json'
        }));

        // 如果有海报文件，则添加到'file'字段
        // 从ImageUpload组件获取实际的文件对象
        if (form.value.posterUrl && Array.isArray(form.value.posterUrl) && form.value.posterUrl.length > 0) {
          const fileObj = form.value.posterUrl[0];
          if (fileObj.raw) {
            formData.append('file', fileObj.raw);
          }
        } else if (form.value.posterUrl && typeof form.value.posterUrl === 'object' && form.value.posterUrl.raw) {
          formData.append('file', form.value.posterUrl.raw);
        }

        addProductActivity(formData).then(response => {
          proxy.$modal.msgSuccess("新增活动成功");
          open.value = false;
          getList();
        }).catch(error => {
          console.error("新增活动失败:", error);
          proxy.$modal.msgError("新增活动失败");
        });
      }
    }
  });
}

// 活动组选项
const activityGroupOptions = ref([]);

// 获取活动组列表
async function fetchActivityGroupList() {
  try {
    // 修复：添加分页参数，避免返回空数据
    const response = await listGroup({
      pageNum: 1,
      pageSize: 100
    });
    activityGroupOptions.value = response.rows.map(item => ({
      value: item.id,
      label: item.name
    }));
  } catch (error) {
    console.error('获取活动组列表失败:', error);
    proxy.$modal.msgError('获取活动组列表失败');
  }
}

// 页面初始化加载数据
onMounted(() => {
  // 加载活动组列表
  fetchActivityGroupList();
  // 其他初始化逻辑...
});

getList();
</script>